<?php
class Shuffler_Collection_Lazy extends Shuffler_Collection
{
    /**
    * @var Shuffler_Mapper_Mapping_Collection
    */
    protected $mapping;
    
    /**
    * @var Shuffler_Model
    */
    protected $model;
    
    /**
    * @var bool wether this lazycollection has been loaded ( initialized )
    */
    protected $loaded = false;
    
    /**
    * @var count of records
    */
    protected $count;
    
    /**
    * @param Shuffler_Mapper_Mapping_Collection
    * @param Shuffler_Model
    */
    public function __construct( Shuffler_Mapper_Mapping_Collection $mapping, Shuffler_Model $model )
    {
        parent::__construct( array(), $mapping->getClass() );
        $this->mapping = $mapping;
        $this->model = $model;
    }
    
    /**
    * @return ArrayIterator
    */
    public function getModels()
    {
        $this->load();
        return parent::getModels();
    }
    
    /**
    * @return bool
    */
    public function contains( $compare )
    {
        $this->load();
        return parent::contains( $compare );
    }
    
    /**
    * Get the model at a specific index in the results array
    * 
    * @param integer index
    * 
    * @return Shuffler_Model
    */
    public function getModelAtIndex( $index )
    {
        $this->load();
        return parent::getModelAtIndex( $index );
    }
    
    /**
    * @return Shuffler_Collection
    */
    public function getModel()
    {
        return $this->model;
    }
    
    /**
    * Removes a certain model from the collection
    * @param Shuffler_Model to remove
    */
    public function removeModel( Shuffler_Model $model )
    {
        $this->load();
        return parent::removeModel( $model );
    }
    
    /**
    * Get # of models this collection currently has
    * 
    * @return int count
    */
    public function count()
    {
        if( isset( $this->count ) )
        {
            return $this->count;
        }
        if( false === $this->loaded )
        {
            $this->count = $this->mapping->countCollection( $this->getModel() );
        }
        else
        {
            $this->count = parent::count();
        }
        return $this->count;
    }
    
    public function load()
    {
        if( false === $this->loaded )
        {
            $this->loaded = true; 
            $this->merge( $this->mapping->loadCollection( $this->getModel() ) );
        }
    }
}